package com.simpilemvc.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 设置字符集
 * @author yangwenkui
 * @version v2.0
 * @time 2016年10月26日 下午10:48:35
 */
public class CharacterEncodingFilter implements Filter{
	
	private String encoding;
	private boolean forceEncoding = false;

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		if(this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)){
			request.setCharacterEncoding(this.encoding);
			if(this.forceEncoding){
				response.setCharacterEncoding(this.encoding);
			}
		}
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding = filterConfig.getInitParameter("encoding");
		this.forceEncoding = Boolean.valueOf(filterConfig.getInitParameter("forceEncoding"));
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

}
